#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

static void handle_SIGPIPE(int sig)
{
    printf("Child received SIGPIPE signal.\n");
    _exit(0);
}
int main()
{
    int pipefd[2];
    if (pipe(pipefd) == -1)
    {
        perror("pipe");
        exit(1);
    }

    pid_t pid = fork();
    if (pid == -1)
    {
        perror("fork");
        exit(1);
    }
    else if (pid == 0)
    {
        close(pipefd[0]);
        if (signal(SIGPIPE, handle_SIGPIPE) == SIG_ERR)
        {
            perror("signal");
            exit(1);
        }
        while (true)
        {
            write(pipefd[1], "data", 4);
        }
    }
    else
    {
        close(pipefd[1]);
        close(pipefd[0]);
        int status;
        waitpid(pid, &status, 0);
        if (WIFEXITED(status))
        {
            printf("Child exited normally with status %d.\n", WEXITSTATUS(status));
        }
        else if (WIFSIGNALED(status))
        {
            if (WTERMSIG(status) == SIGPIPE)
            {
                printf("Child terminated by SIGPIPE signal.\n");
            }
            else
            {
                printf("Child terminated by signal %d.\n", WTERMSIG(status));
            }
        }
        else
        {
            printf("Child terminated abnormally.\n");
        }
    }
    return 0;
}

// static void Usage(string proc)
// {

// }
// int main(int argc, char* argv[])
// {
//     cout<<"begin"<<endl;
//     // sleep(1);
//     // raise(8);
//     abort();
//     return 0;
// }